import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { authApi } from '@/api'
import type { User, LoginRequest, RegisterRequest } from '@/types'

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))
  const isLoading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!user.value)
  const userId = computed(() => user.value?.id || 0)
  const username = computed(() => user.value?.username || '')
  const nickname = computed(() => user.value?.nickname || '')

  // 登录
  const login = async (loginData: LoginRequest) => {
    try {
      isLoading.value = true
      const response = await authApi.login(loginData)
      
      if (response.code === 200) {
        token.value = response.data.token
        user.value = response.data.user
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('user', JSON.stringify(response.data.user))
        return { success: true }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error: any) {
      console.error('登录失败:', error)
      return { success: false, message: error.response?.data?.message || '登录失败' }
    } finally {
      isLoading.value = false
    }
  }

  // 注册
  const register = async (registerData: RegisterRequest) => {
    try {
      isLoading.value = true
      const response = await authApi.register(registerData)
      
      if (response.code === 200) {
        token.value = response.data.token
        user.value = response.data.user
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('user', JSON.stringify(response.data.user))
        return { success: true }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error: any) {
      console.error('注册失败:', error)
      return { success: false, message: error.response?.data?.message || '注册失败' }
    } finally {
      isLoading.value = false
    }
  }

  // 获取用户信息
  const fetchUserProfile = async () => {
    try {
      const response = await authApi.getProfile()
      if (response.code === 200) {
        user.value = response.data
        localStorage.setItem('user', JSON.stringify(response.data))
        return true
      }
      return false
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return false
    }
  }

  // 登出
  const logout = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  // 初始化用户信息
  const initUser = () => {
    const savedUser = localStorage.getItem('user')
    if (savedUser && token.value) {
      try {
        user.value = JSON.parse(savedUser)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        logout()
      }
    }
  }

  // 刷新Token
  const refreshToken = async () => {
    try {
      const response = await authApi.refreshToken()
      if (response.code === 200) {
        token.value = response.data.token
        localStorage.setItem('token', response.data.token)
        return true
      }
      return false
    } catch (error) {
      console.error('刷新Token失败:', error)
      logout()
      return false
    }
  }

  return {
    // 状态
    user,
    token,
    isLoading,
    // 计算属性
    isLoggedIn,
    userId,
    username,
    nickname,
    // 方法
    login,
    register,
    fetchUserProfile,
    logout,
    initUser,
    refreshToken
  }
})
